import 'dart:async';

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import 'package:pull_to_refresh_new/pull_to_refresh.dart';
import 'package:sprintf/sprintf.dart';
import 'package:scan/scan.dart'; 

import '../../core/controller/app_controller.dart';
import '../../core/controller/im_controller.dart';
import '../../core/im_callback.dart';
import '../../routes/app_navigator.dart';
import '../contacts/add_by_search/add_by_search_logic.dart';
import '../home/home_logic.dart';

class ConversationLogic extends GetxController {
  final popCtrl = CustomPopupMenuController();
  final list = <ConversationInfo>[].obs;
  final imLogic = Get.find<IMController>();
  final homeLogic = Get.find<HomeLogic>();
  final appLogic = Get.find<AppController>();
  final refreshController = RefreshController();
  final tempDraftText = <String, String>{};
  final pageSize = 400;

  final imStatus = IMSdkStatus.connectionSucceeded.obs;
  bool reInstall = false;

  final onChangeConversations = <ConversationInfo>[];
  Timer? _changeDebounce;
  final List<ConversationInfo> _pendingChanges = [];
  bool _isProcessingChanges = false;
  
    // 滑动状态管理
  final Set<String> _slidedItems = <String>{};
  final Map<String, double> _dragOffsets = <String, double>{}; // 拖动偏移量管理
  final Map<String, double> _lastDragOffsets = <String, double>{}; // 上次拖动结束时的偏移量
  final Map<String, String> _slideDirection = <String, String>{}; // 滑动方向管理：'left' 或 'right'

  // 检查指定会话是否处于滑动状态
  bool isSlided(String conversationID) {
    return _slidedItems.contains(conversationID);
  }

  // 获取拖动偏移量
  double getDragOffset(String conversationID) {
    return _dragOffsets[conversationID] ?? 0.0;
  }

  // 获取滑动方向
  String getSlideDirection(String conversationID) {
    return _slideDirection[conversationID] ?? '';
  }

  // 设置拖动偏移量
  void setDragOffset(String conversationID, double offset) {
    // 支持双向滑动：向左最多240像素（3个按钮），向右最多160像素（2个按钮）
    final clampedOffset = offset.clamp(-240.0, 0.0);
    _dragOffsets[conversationID] = clampedOffset;
    
    // 记录滑动方向
    if (clampedOffset < 0) {
      _slideDirection[conversationID] = 'left';
    } else if (clampedOffset > 0) {
      _slideDirection[conversationID] = 'right';
    }
    
    // 精确更新指定会话
    update(['slide_$conversationID']);
  }

  // 开始拖动
  void startDrag(String conversationID) {
    print('开始拖动: $conversationID, 当前偏移量: ${_dragOffsets[conversationID] ?? 0.0}');
    
    // 重置其他项的状态
    final otherItems = _slidedItems.where((id) => id != conversationID).toList();
    for (String otherId in otherItems) {
      _slidedItems.remove(otherId);
      _dragOffsets.remove(otherId);
      _lastDragOffsets.remove(otherId);
      _slideDirection.remove(otherId);
      update(['slide_$otherId']); // 精确更新其他项
    }
    
    // 保持当前项的偏移量，不重置为0，实现累计拖动
    // 如果当前项没有偏移量记录，则初始化为0
    if (!_dragOffsets.containsKey(conversationID)) {
      _dragOffsets[conversationID] = 0.0;
    }
    
    // 记录开始拖动时的偏移量作为基准
    _lastDragOffsets[conversationID] = _dragOffsets[conversationID] ?? 0.0;
    
    update(['slide_$conversationID']);
  }

 // 拖动更新
  void updateDrag(String conversationID, double delta) {
    // 基于上次拖动结束时的位置进行累计
    final lastOffset = _lastDragOffsets[conversationID] ?? 0.0;
    final currentDelta = (_dragOffsets[conversationID] ?? lastOffset) - lastOffset;
    final newOffset = lastOffset + currentDelta + delta;
    
    print('拖动更新: $conversationID, 上次偏移: $lastOffset, 当前增量: $delta, 新偏移: $newOffset');
    
    setDragOffset(conversationID, newOffset);
  }

   // 结束拖动
  void endDrag(String conversationID, double velocity) {
    final currentOffset = _dragOffsets[conversationID] ?? 0.0;
    
    print('结束拖动: $conversationID, 偏移量: $currentOffset, 速度: $velocity');
    
    // 根据拖动距离和速度决定最终状态
    if (currentOffset < -160) {
      // 左滑：显示操作按钮（标为未读、不显示、删除）
      _slidedItems.add(conversationID);
      _dragOffsets[conversationID] = -240.0; // 3个按钮的宽度
      _slideDirection[conversationID] = 'left';
      print('显示左滑操作按钮: $conversationID');
    } else if (currentOffset < -80) {
      // 右滑：显示操作按钮（标为未读、置顶）
      _slidedItems.add(conversationID);
      _dragOffsets[conversationID] = -160.0; // 2个按钮的宽度
      _slideDirection[conversationID] = 'left';
      print('显示右滑操作按钮: $conversationID');
    } else if (currentOffset.abs() < 80 || velocity > 100) {
      // 如果偏移量很小，则完全隐藏
      _slidedItems.remove(conversationID);
      _dragOffsets[conversationID] = 0.0;
      _slideDirection.remove(conversationID);
      print('完全隐藏操作按钮: $conversationID');
    } else{
      // 保持当前位置，允许下次继续拖动
      print('保持当前位置: $conversationID, 偏移量: $currentOffset');
    }
    
    // 更新上次拖动结束时的偏移量
    _lastDragOffsets[conversationID] = _dragOffsets[conversationID] ?? 0.0;
    
    // 精确更新指定会话
    update(['slide_$conversationID']);
  }
  // 设置会话的滑动状态
  void setSlideState(String conversationID, bool isSlided, {String direction = 'left'}) {
    if (isSlided) {
      // 设置新的滑动项时，先重置其他项
      resetAllSlideStates();
      _slidedItems.add(conversationID);
      if (direction == 'right') {
        _dragOffsets[conversationID] = 160.0;
        _slideDirection[conversationID] = 'right';
      } else {
        _dragOffsets[conversationID] = -240.0;
        _slideDirection[conversationID] = 'left';
      }
      _lastDragOffsets[conversationID] = _dragOffsets[conversationID] ?? 0.0;
    } else {
      _slidedItems.remove(conversationID);
      _dragOffsets[conversationID] = 0.0;
      _lastDragOffsets[conversationID] = 0.0;
      _slideDirection.remove(conversationID);
    }
    update(['slide_$conversationID']);
  }

  // 重置所有滑动状态
  void resetAllSlideStates() {
    print('重置所有滑动状态');
    final allSlidedItems = List<String>.from(_slidedItems);
    final allDragItems = List<String>.from(_dragOffsets.keys);
    final allLastDragItems = List<String>.from(_lastDragOffsets.keys);
    final allDirectionItems = List<String>.from(_slideDirection.keys);
    
    _slidedItems.clear();
    _dragOffsets.clear();
    _lastDragOffsets.clear();
    _slideDirection.clear();
    
    // 精确更新所有受影响的项
    for (String id in {...allSlidedItems, ...allDragItems, ...allLastDragItems, ...allDirectionItems}) {
      update(['slide_$id']);
    }
  }

  // 重置指定会话的滑动状态
  void resetSlideState(String conversationID) {
    print('重置滑动状态: $conversationID');
    bool needUpdate = false;
    
    if (_slidedItems.remove(conversationID)) {
      needUpdate = true;
    }
    if (_dragOffsets.remove(conversationID) != null) {
      needUpdate = true;
    }
    if (_lastDragOffsets.remove(conversationID) != null) {
      needUpdate = true;
    }
    if (_slideDirection.remove(conversationID) != null) {
      needUpdate = true;
    }
    
    if (needUpdate) {
      update(['slide_$conversationID']);
    }
  }
    // 隐藏会话
  Future<void> hideConversation(ConversationInfo info) async {
    try {
      print('隐藏会话: ${info.conversationID}');
      
      // 显示加载提示
      EasyLoading.show(status: '正在隐藏会话...');
      
      // 调用 OpenIM SDK 隐藏会话
      // 注意：如果 hideConversation 方法不存在，可以使用其他方式实现隐藏功能
      // 比如设置会话为免打扰或者本地标记为隐藏
      
      // 从列表中移除
      list.removeWhere((e) => e.conversationID == info.conversationID);
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
      
      // 更新UI
      update();
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示成功提示
      EasyLoading.showSuccess('会话已隐藏');
      
      print('隐藏会话成功: ${info.conversationID}');
    } catch (e) {
      print('隐藏会话失败: ${info.conversationID}, 错误: $e');
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示错误提示
      EasyLoading.showError('隐藏会话失败: ${e.toString()}');
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
    }
  }

  // 删除会话
  Future<void> deleteConversation(ConversationInfo info) async {
    
    // 显示确认对话框
    final confirm = await Get.dialog(CustomDialog(
      title: StrRes.confirmDeleteConversation,
      content: sprintf(StrRes.confirmDeleteConversationContent, [getShowName(info)]),
      rightText: StrRes.delete,
      leftText: StrRes.cancel,
    ));
    if (confirm != true) {
      return; // 用户取消删除
    }
    try {
      print('删除会话: ${info.conversationID}');
      // 调用 OpenIM SDK 删除会话和所有消息
      await OpenIM.iMManager.conversationManager.deleteConversationAndDeleteAllMsg(
        conversationID: info.conversationID,
      );
      // 从列表中移除
      list.removeWhere((e) => e.conversationID == info.conversationID);
      // 重置滑动状态
      resetSlideState(info.conversationID);
      // 更新UI
      update();
      print('删除会话成功: ${info.conversationID}');
    } catch (e) {
      print('删除会话失败: ${info.conversationID}, 错误: $e');
      resetSlideState(info.conversationID);
    }
  }

  // 置顶会话
  Future<void> pinConversation(ConversationInfo info) async {
    try {
      print('置顶会话: ${info.conversationID}');
      
      // 显示加载提示
      EasyLoading.show(status: info.isPinned == true ? '取消置顶中...' : '置顶中...');
      
      // 调用 OpenIM SDK 设置置顶状态
      final req = ConversationReq(isPinned: !(info.isPinned == true));
      await OpenIM.iMManager.conversationManager.setConversation(
        info.conversationID,
        req
      );
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示成功提示
      EasyLoading.showSuccess(info.isPinned == true ? StrRes.cancelTop : StrRes.top);
      
      print('置顶会话成功: ${info.conversationID}');
    } catch (e) {
      print('置顶会话失败: ${info.conversationID}, 错误: $e');
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示错误提示
      EasyLoading.showError('操作失败: ${e.toString()}');
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
    }
  }

  // 标为未读
  Future<void> markAsUnread(ConversationInfo info) async {
    try {
      print('标为未读: ${info.conversationID}');
      // 显示加载提示
      EasyLoading.show(status: '标为未读中...');
      // 调用 OpenIM SDK 标记为未读
      // 注意：这里可能需要根据实际的SDK API进行调整
      final req = ConversationReq(groupAtType: 1);
       await OpenIM.iMManager.conversationManager.setConversation(
        info.conversationID,
        req
      );
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示成功提示
      EasyLoading.showSuccess('已标为未读');
      
      print('标为未读成功: ${info.conversationID}');
    } catch (e) {
      print('标为未读失败: ${info.conversationID}, 错误: $e');
      
      // 隐藏加载提示
      EasyLoading.dismiss();
      
      // 显示错误提示
      EasyLoading.showError('操作失败: ${e.toString()}');
      
      // 重置滑动状态
      resetSlideState(info.conversationID);
    }
  }
  @override
  void onInit() {
    getFirstPage();
    imLogic.conversationAddedSubject.listen(onChanged);
    imLogic.conversationChangedSubject.listen(onChanged);
    imLogic.imSdkStatusSubject.listen((value) async {
      final status = value.status;
      final appReInstall = value.reInstall;
      final progress = value.progress;
      imStatus.value = status;

      if (status == IMSdkStatus.syncStart) {
        reInstall = appReInstall;
        if (reInstall) {
          EasyLoading.showProgress(0, status: StrRes.synchronizing);
        }
      }

      Logger.print('IM SDK Status: $status, reinstall: $reInstall, progress: $progress');

      if (status == IMSdkStatus.syncProgress && reInstall) {
        final p = (progress!).toDouble() / 100.0;

        EasyLoading.showProgress(p, status: '${StrRes.synchronizing}(${(p * 100.0).truncate()}%)');
      } else if (status == IMSdkStatus.syncEnded || status == IMSdkStatus.syncFailed) {
        EasyLoading.dismiss();
        if (reInstall) {
          onRefresh();
          reInstall = false;
        }
      }
    });
    super.onInit();
  }

  @override
  void onClose() {
    list.clear();
    reInstall = false;
    try { _changeDebounce?.cancel(); } catch (_) {}
    _pendingChanges.clear();
    super.onClose();
  }

  void onChanged(List<ConversationInfo> newList) async {
    _pendingChanges.addAll(newList);
    _changeDebounce?.cancel();
    _changeDebounce = Timer(const Duration(milliseconds: 150), _processChangeBatch);
  }

  void promptSoundOrNotification(ConversationInfo info) {
    if (imLogic.userInfo.value.globalRecvMsgOpt == 0 &&
        info.recvMsgOpt == 0 &&
        info.unreadCount > 0 &&
        info.latestMsg?.sendID != OpenIM.iMManager.userID) {
      appLogic.promptSoundOrNotification(info.latestMsg!.seq!);
    }
  }

  String getConversationID(ConversationInfo info) {
    return info.conversationID;
  }

  String? getPrefixTag(ConversationInfo info) {
    if (info.groupAtType == GroupAtType.groupNotification) {
      return '[${StrRes.groupAc}]';
    }

    return null;
  }

  String getContent(ConversationInfo info) {
    try {
      if (null != info.draftText && '' != info.draftText) {
        var map = json.decode(info.draftText!);
        String text = map['text'];
        if (text.isNotEmpty) {
          return text;
        }
      }

      if (null == info.latestMsg) return "";

      final text = IMUtils.parseNtf(info.latestMsg!, isConversation: true);
      if (text != null) return text;
      if (info.isSingleChat || info.latestMsg!.sendID == OpenIM.iMManager.userID)
        return IMUtils.parseMsg(info.latestMsg!, isConversation: true);

      return "${info.latestMsg!.senderNickname}: ${IMUtils.parseMsg(info.latestMsg!, isConversation: true)} ";
    } catch (e, s) {
      Logger.print('------e:$e s:$s');
    }
    return '[${StrRes.unsupportedMessage}]';
  }

  String? getAvatar(ConversationInfo info) {
    return info.faceURL;
  }

  bool isGroupChat(ConversationInfo info) {
    return info.isGroupChat;
  }

  String getShowName(ConversationInfo info) {
    if (info.showName == null || info.showName.isBlank!) {
      return info.userID!;
    }
    return info.showName!;
  }

  String getTime(ConversationInfo info) {
    return IMUtils.getChatTimeline(info.latestMsgSendTime!);
  }

  int getUnreadCount(ConversationInfo info) {
    return info.unreadCount;
  }

  bool existUnreadMsg(ConversationInfo info) {
    return getUnreadCount(info) > 0;
  }

  bool isUserGroup(int index) => list.elementAt(index).isGroupChat;

  String? get imSdkStatus {
    switch (imStatus.value) {
      case IMSdkStatus.syncStart:
      case IMSdkStatus.synchronizing:
      case IMSdkStatus.syncProgress:
        return StrRes.synchronizing;
      case IMSdkStatus.syncFailed:
        return StrRes.syncFailed;
      case IMSdkStatus.connecting:
        return StrRes.connecting;
      case IMSdkStatus.connectionFailed:
        return StrRes.connectionFailed;
      case IMSdkStatus.connectionSucceeded:
      case IMSdkStatus.syncEnded:
        return null;
    }
  }

  bool get isFailedSdkStatus =>
      imStatus.value == IMSdkStatus.connectionFailed || imStatus.value == IMSdkStatus.syncFailed;

  void _sortConversationList() => OpenIM.iMManager.conversationManager.simpleSort(list);

  void onRefresh() async {
    late List<ConversationInfo> list;
    try {
      list = await _request();
      this.list.assignAll(list);

      if (list.isEmpty || list.length < pageSize) {
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
    } finally {
      refreshController.refreshCompleted();
    }
  }

  static Future<List<ConversationInfo>> getConversationFirstPage() async {
    final result = await OpenIM.iMManager.conversationManager.getConversationListSplit(offset: 0, count: 400);
    
    // 过滤掉非好友的单聊会话
    return await _filterNonFriendConversationsStatic(result);
  }

  // 静态方法：过滤非好友会话
  static Future<List<ConversationInfo>> _filterNonFriendConversationsStatic(List<ConversationInfo> list) async {
    final filteredList = <ConversationInfo>[];
    
    for (final conversation in list) {
      // 只检查单聊会话，群聊会话不需要检查
      if (conversation.conversationType == ConversationType.single) {
        try {
          // 获取好友信息来验证是否为好友
          final friendsInfo = await OpenIM.iMManager.friendshipManager.getFriendsInfo(
            userIDList: [conversation.userID!],
          );
          
          // 如果是好友，则添加到过滤后的列表中
          if (friendsInfo.isNotEmpty) {
            Logger.print('允许加载好友会话(首页): ${conversation.userID}');
            filteredList.add(conversation);
          } else {
            Logger.print('拒绝加载陌生人会话(首页): ${conversation.userID}');
          }
        } catch (e) {
          // 如果获取好友信息失败，也拒绝加载会话
          Logger.print('获取好友信息失败，拒绝加载会话(首页): ${conversation.userID}, error: $e');
        }
      } else {
        // 群聊会话直接添加
        filteredList.add(conversation);
      }
    }
    
    return filteredList;
  }

  Future<List<ConversationInfo>> _enrichConversationsWithDomain(List<ConversationInfo> list) async {
    final tasks = <Future<void>>[];
    for (final conv in list) {
      if (conv.conversationType == ConversationType.single && conv.userID != null && conv.userID!.isNotEmpty) {
        tasks.add(() async {
          try {
            final profile = await Apis.getUserProfileByOpenIMID(conv.userID!);
            if (profile != null) {
              conv.showName = profile.nickname ?? conv.showName;
              conv.faceURL = profile.faceURL ?? conv.faceURL;
            }
          } catch (_) {}
        }());
      }
    }
    await Future.wait(tasks);
    return list;
  }

  List<ConversationInfo> _uniqueByConversationID(List<ConversationInfo> items) {
    final map = <String, ConversationInfo>{};
    for (final c in items) {
      final id = c.conversationID;
      if (id.isNotEmpty) {
        map[id] = c;
      }
    }
    return map.values.toList();
  }

  Future<void> _processChangeBatch() async {
    if (_isProcessingChanges) return;
    _isProcessingChanges = true;
    try {
      if (_pendingChanges.isEmpty) return;
      if (reInstall) {
        onChangeConversations.addAll(_pendingChanges);
        _pendingChanges.clear();
        return;
      }
      final unique = _uniqueByConversationID(_pendingChanges);
      _pendingChanges.clear();
      final ids = unique.map((e) => e.conversationID).toSet();
      list.removeWhere((e) => ids.contains(e.conversationID));
      final enriched = await _enrichConversationsWithDomain(unique);
      if (enriched.length > pageSize) {
        var tempList = List<ConversationInfo>.from(enriched);
        while (tempList.isNotEmpty) {
          final end = tempList.length < pageSize ? tempList.length : pageSize;
          final temp = tempList.sublist(0, end);
          list.insertAll(0, temp);
          _sortConversationList();
          tempList.removeRange(0, end);
        }
      } else {
        list.insertAll(0, enriched);
        _sortConversationList();
      }
    } finally {
      _isProcessingChanges = false;
    }
  }

  void getFirstPage() async {
    final result = homeLogic.conversationsAtFirstPage;
    final enriched = await _enrichConversationsWithDomain(result);

    list.assignAll(enriched);
    _sortConversationList();
  }

  void clearConversations() {
    list.clear();
  }

  _request() async {
    final temp = <ConversationInfo>[];

    while (true) {
      var result = await OpenIM.iMManager.conversationManager.getConversationListSplit(
        offset: temp.length,
        count: pageSize,
      );
      
      // 过滤掉非好友的单聊会话
      result = await _filterNonFriendConversations(result);
      
      if (onChangeConversations.isNotEmpty) {
        final bSet = Set.from(onChangeConversations);

        Logger.print('replace conversation: [${onChangeConversations.length}], $bSet');

        for (int i = 0; i < result.length; i++) {
          final info = result[i];

          if (bSet.contains(info)) {
            result[i] = onChangeConversations[onChangeConversations.indexOf(info)];
          }
        }
      }
      temp.addAll(result);

      if (result.length < pageSize) {
        break;
      }
    }
    onChangeConversations.clear();

    final enriched = await _enrichConversationsWithDomain(temp);
    return enriched;
  }

  // 过滤非好友会话
  Future<List<ConversationInfo>> _filterNonFriendConversations(List<ConversationInfo> list) async {
    final filteredList = <ConversationInfo>[];
    
    for (final conversation in list) {
      // 只检查单聊会话，群聊会话不需要检查
      if (conversation.conversationType == ConversationType.single) {
        try {
          // 获取好友信息来验证是否为好友
          final friendsInfo = await OpenIM.iMManager.friendshipManager.getFriendsInfo(
            userIDList: [conversation.userID!],
          );
          
          // 如果是好友，则添加到过滤后的列表中
          if (friendsInfo.isNotEmpty) {
            Logger.print('允许加载好友会话: ${conversation.userID}');
            filteredList.add(conversation);
          } else {
            Logger.print('拒绝加载陌生人会话: ${conversation.userID}');
          }
        } catch (e) {
          // 如果获取好友信息失败，也拒绝加载会话
          Logger.print('获取好友信息失败，拒绝加载会话: ${conversation.userID}, error: $e');
        }
      } else {
        // 群聊会话直接添加
        filteredList.add(conversation);
      }
    }
    
    return filteredList;
  }

  bool isValidConversation(ConversationInfo info) {
    return info.isValid;
  }

  static Future<ConversationInfo> _createConversation({
    required String sourceID,
    required int sessionType,
  }) =>
      LoadingView.singleton.wrap(
          asyncFunction: () => OpenIM.iMManager.conversationManager.getOneConversation(
                sourceID: sourceID,
                sessionType: sessionType,
              ));

  Future<bool> _jumpOANtf(ConversationInfo info) async {
    if (info.conversationType == ConversationType.notification) {
      return true;
    }
    return false;
  }

  void toChat({
    bool offUntilHome = true,
    String? userID,
    String? groupID,
    String? nickname,
    String? faceURL,
    int? sessionType,
    ConversationInfo? conversationInfo,
    Message? searchMessage,
  }) async {
    conversationInfo ??= await _createConversation(
      sourceID: userID ?? groupID!,
      sessionType: userID == null ? sessionType! : ConversationType.single,
    );

    if (await _jumpOANtf(conversationInfo)) return;

    await AppNavigator.startChat(
      offUntilHome: offUntilHome,
      draftText: conversationInfo.draftText,
      conversationInfo: conversationInfo,
      searchMessage: searchMessage,
    );

    bool equal(e) => e.conversationID == conversationInfo?.conversationID;

    var groupAtType = list.firstWhereOrNull(equal)?.groupAtType;
    if (groupAtType != GroupAtType.atNormal) {
      OpenIM.iMManager.conversationManager.resetConversationGroupAtType(
        conversationID: conversationInfo.conversationID,
      );
    }
  }

  addFriend() => AppNavigator.startAddContactsBySearch(searchType: SearchType.user);

  createGroup() => AppNavigator.startCreateGroup(defaultCheckedList: [OpenIM.iMManager.userInfo]);

  addGroup() => AppNavigator.startAddContactsBySearch(searchType: SearchType.group);


  void globalSearch() async {
    final result = await AppNavigator.startGlobalSearch();
    debugPrint('全局搜索返回结果: $result');
    // 处理全局搜索返回的结果
    if (result != null && result is Map<String, dynamic>) {
      final action = result['action'];
      
      if (action == 'jumpToMessage') {
        debugPrint('进入jumpToMessage逻辑');
        final conversationID = result['conversationID'] as String?;
        final message = result['message'] as Message?;
        debugPrint("全局搜索返回结果: $conversationID $message");
        
        if (conversationID != null && message != null) {
          debugPrint("conversationID: $conversationID");
            debugPrint("会话列表中的所有conversationID:,list.length=${list.length}");
          for (int i = 0; i < list.length; i++) {
            debugPrint(" my conversion [$i] ${list[i].conversationID}");
          }
          // 根据conversationID找到对应的会话信息
          final conversation = list.firstWhereOrNull(
            (conv) => conv.conversationID == conversationID,
          );
          debugPrint("my: $conversation");
          
          if (conversation != null) {
            // 跳转到聊天页面并传递搜索消息
            debugPrint("跳转到聊天页面并传递搜索消息: $conversationID $message");
            toChat(
              conversationInfo: conversation,
              searchMessage: message,
            );
          } else {
            // 如果会话列表中没有找到，创建新的会话信息
            await _handleJumpToMessageWithoutConversation(conversationID, message);
          }
        }
      }
    }
  }
  
  // 处理没有现有会话的消息跳转
  Future<void> _handleJumpToMessageWithoutConversation(String conversationID, Message message) async {
    try {
      ConversationInfo? conversationInfo;
      
      if (message.sessionType == ConversationType.single) {
        // 单聊：根据消息确定对方用户ID
        final otherUserID = message.sendID == OpenIM.iMManager.userID 
            ? message.recvID 
            : message.sendID;
            
        if (otherUserID != null) {
          conversationInfo = await _createConversation(
            sourceID: otherUserID,
            sessionType: ConversationType.single,
          );
        }
      } else if (message.sessionType == ConversationType.group) {
        // 群聊
        if (message.groupID != null) {
          conversationInfo = await _createConversation(
            sourceID: message.groupID!,
            sessionType: ConversationType.group,
          );
        }
      }
      
      if (conversationInfo != null) {
        toChat(
          conversationInfo: conversationInfo,
          searchMessage: message,
        );
      } else {
        IMViews.showToast('无法找到对应的会话');
      }
    } catch (e) {
      print('创建会话失败: $e');
      IMViews.showToast('跳转失败');
    }
  }

   // 新增扫一扫功能
  void scan() async {
    try {
      // 检查相机权限
      Permissions.camera(() async {
        // 导航到扫描页面
        final result = await AppNavigator.startScan();
        
        if (result != null && result.isNotEmpty) {
          // 处理扫描结果
          _handleScanResult(result);
        }
      });
    } catch (e) {
      print('扫描失败: $e');
      IMViews.showToast('扫描失败');
    }
  }
  // 处理扫描结果
  void _handleScanResult(String result) {
  print('扫描结果: $result');
  
  try {
    // 尝试解析为URI
    Uri? uri;
    if (result.startsWith('http://') || result.startsWith('https://') || result.startsWith('paxiy://')) {
      uri = Uri.tryParse(result);
    }
    
    String? userID;
    String? groupID;
    
    if (uri != null) {
      // 处理新的自定义schema格式的群组邀请链接
      if (uri.scheme == 'paxiy' && uri.host == 'group' && uri.path.startsWith('/invite')) {
        groupID = uri.queryParameters['groupId'];
        final inviterUserId = uri.queryParameters['inviter'];
        
        if (groupID != null && groupID.isNotEmpty) {
          print('识别到群组邀请链接 - 群组ID: $groupID, 邀请者: $inviterUserId');
          _autoJoinGroup(groupID);
          return;
        }
      }
      // 处理HTTPS格式的群组邀请链接
      else if (uri.scheme == 'https' && uri.host == 'paxiy.app' && uri.path.startsWith('/group/invite')) {
        groupID = uri.queryParameters['groupId'];
        final inviterUserId = uri.queryParameters['inviter'];
        
        if (groupID != null && groupID.isNotEmpty) {
          print('识别到HTTPS群组邀请链接 - 群组ID: $groupID, 邀请者: $inviterUserId');
          _autoJoinGroup(groupID);
          return;
        }
      }
      // 处理旧格式的群组链接（兼容性）
      else if (result.contains('io.openim.app/joinGroup/')) {
        groupID = result.split('io.openim.app/joinGroup/').last;
        if (groupID.isNotEmpty) {
          print('识别到旧格式群组链接 - 群组ID: $groupID');
          _autoJoinGroup(groupID);
          return;
        }
      }
      // 处理旧格式的用户链接（兼容性）
      else if (result.contains('io.openim.app/addFriend/')) {
        userID = result.split('io.openim.app/addFriend/').last;
        if (userID.isNotEmpty) {
          print('识别到旧格式用户链接 - 用户ID: $userID');
          PackageBridge.scanBridge?.scanOutUserID(userID);
          IMViews.showToast('正在打开用户资料...');
          return;
        }
      }
      // 处理URL格式的二维码（通用参数）
      else {
        userID = uri.queryParameters['userID'];
        groupID = uri.queryParameters['groupID'];
      }
    } else {
      // 处理简单格式的二维码
      if (result.contains('userID=')) {
        userID = _extractUserID(result);
      } else if (result.contains('groupID=')) {
        groupID = _extractGroupID(result);
      }
    }
    
    if (userID != null && userID.isNotEmpty) {
      // 用户二维码 - 跳转到用户资料页面进行添加好友
      print('识别到用户ID: $userID');
      PackageBridge.scanBridge?.scanOutUserID(userID);
      IMViews.showToast('正在打开用户资料...');
    } else if (groupID != null && groupID.isNotEmpty) {
      // 群组二维码 - 自动加入群聊
      print('识别到群组ID: $groupID');
      _autoJoinGroup(groupID);
    } else {
      // 尝试其他可能的格式
      if (_tryParseAlternativeFormats(result)) {
        return;
      }
      
      // 无法识别的二维码格式
      print('无法识别的二维码格式: $result');
      IMViews.showToast('无法识别的二维码格式');
    }
  } catch (e) {
    print('处理扫描结果时出错: $e');
    IMViews.showToast('处理扫描结果失败');
  }
}
  // 自动加入群聊
  Future<void> _autoJoinGroup(String groupID) async {
  try {
    IMViews.showToast('正在获取群组信息...');
    
    // 1. 获取群组信息
    final groupsInfo = await OpenIM.iMManager.groupManager.getGroupsInfo(
      groupIDList: [groupID],
    );
    
    if (groupsInfo.isEmpty) {
      IMViews.showToast('群组不存在或已解散');
      return;
    }
    
    final groupInfo = groupsInfo.first;
    
    // 2. 检查是否已经是群成员
    final isAlreadyMember = await OpenIM.iMManager.groupManager.isJoinedGroup(
      groupID: groupID,
    );
    
    if (isAlreadyMember) {
      // 已经是群成员，直接进入群聊
      IMViews.showToast('您已经是群成员，正在进入群聊...');
      _enterGroupChat(groupInfo);
      return;
    }
    
    // 3. 显示加群确认对话框
    _showJoinGroupConfirmDialog(groupInfo);
    
  } catch (e) {
    print('获取群组信息失败: $e');
    IMViews.showToast('获取群组信息失败，请稍后重试');
  }
}

  // 显示加群确认对话框
  void _showJoinGroupConfirmDialog(GroupInfo groupInfo) {
  Get.dialog(
    Material(
      color: Colors.transparent,
      child: Center(
        child: Container(
          width: 300.w,
          margin: EdgeInsets.symmetric(horizontal: 32.w),
          decoration: BoxDecoration(
            color: Styles.c_FFFFFF,
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                blurRadius: 20,
                offset: const Offset(0, 8),
              ),
            ],
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 头部标题
              Container(
                padding: EdgeInsets.only(top: 24.h, bottom: 16.h),
                child: Text(
                  '加入群聊',
                  style: Styles.ts_0C1C33_17sp.copyWith(
                    fontWeight: FontWeight.w600,
                  ),
                ),
              ),
              
              // 群聊信息卡片
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20.w),
                padding: EdgeInsets.all(16.w),
                decoration: BoxDecoration(
                  color: Styles.c_F2F8FF,
                  borderRadius: BorderRadius.circular(12.r),
                ),
                child: Row(
                  children: [
                  // 群头像
                    Container(
  decoration: BoxDecoration(
    borderRadius: BorderRadius.circular(12.r),
    boxShadow: [
      BoxShadow(
        color: Colors.black.withOpacity(0.08),
        blurRadius: 8,
        offset: const Offset(0, 2),
      ),
    ],
  ),
  child: ClipRRect(
    borderRadius: BorderRadius.circular(12.r),
    child: ImageUtil.networkImage(
      url: groupInfo.faceURL ?? '',
      width: 60.w,
      height: 60.w,
      fit: BoxFit.cover,
      errorWidget: Container(
        width: 60.w,
        height: 60.w,
        decoration: BoxDecoration(
          color: Styles.c_F2F8FF,
          borderRadius: BorderRadius.circular(12.r),
        ),
        child: Icon(
          Icons.group,
          size: 30.w,
          color: Styles.c_0089FF,
        ),
      ),
    ),
  ),
),
                    SizedBox(width: 16.w),
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            groupInfo.groupName ?? '',
                            style: Styles.ts_0C1C33_10sp.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                            maxLines: 2,
                            overflow: TextOverflow.ellipsis,
                          ),
                          SizedBox(height: 6.h),
                          Row(
                            children: [
                              Icon(
                                Icons.people_outline,
                                size: 14.w,
                                color: Styles.c_8E9AB0,
                              ),
                              SizedBox(width: 4.w),
                              Text(
                                '${groupInfo.memberCount ?? 0}人',
                                style: Styles.ts_8E9AB0_14sp,
                              ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              
              // 提示文字
              Container(
                padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 16.h),
                child: Text(
                  '确定要加入这个群聊吗？',
                  style: Styles.ts_8E9AB0_14sp,
                  textAlign: TextAlign.center,
                ),
              ),
              
              // 按钮区域
              Container(
                padding: EdgeInsets.fromLTRB(20.w, 0, 20.w, 24.h),
                child: Row(
                  children: [
                    // 取消按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () => Get.back(),
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            color: Styles.c_F2F8FF,
                            borderRadius: BorderRadius.circular(22.r),
                            border: Border.all(
                              color: Styles.c_E8EAEF,
                              width: 1,
                            ),
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '取消',
                            style: Styles.ts_0C1C33_17sp_medium.copyWith(
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ),
                      ),
                    ),
                    SizedBox(width: 12.w),
                    // 加入按钮
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          Get.back();
                          _performJoinGroup(groupInfo);
                        },
                        child: Container(
                          height: 44.h,
                          decoration: BoxDecoration(
                            gradient: LinearGradient(
                              colors: [
                                Styles.c_0089FF,
                                Styles.c_0089FF.withOpacity(0.8),
                              ],
                              begin: Alignment.topCenter,
                              end: Alignment.bottomCenter,
                            ),
                            borderRadius: BorderRadius.circular(22.r),
                            boxShadow: [
                              BoxShadow(
                                color: Styles.c_0089FF.withOpacity(0.3),
                                blurRadius: 8,
                                offset: const Offset(0, 4),
                              ),
                            ],
                          ),
                          alignment: Alignment.center,
                          child: Text(
                            '加入',
                            style: Styles.ts_FFFFFF_17sp_medium.copyWith(
                              fontWeight: FontWeight.w600,
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    ),
    barrierDismissible: true,
  );
}

  // 执行加群操作
  Future<void> _performJoinGroup(GroupInfo groupInfo) async {
  try {
    await LoadingView.singleton.wrap(
      asyncFunction: () async {
        // 根据群组类型选择加入方式
        if (groupInfo.needVerification == GroupVerification.directly) {
          // 直接加入
          await OpenIM.iMManager.groupManager.joinGroup(
            groupID: groupInfo.groupID!,
            reason: '通过扫码加入',
            joinSource: 2, // 扫码加入
          );
          
          IMViews.showToast('加入群聊成功');
          
          // 进入群聊
          _enterGroupChat(groupInfo);
        } else {
          // 需要申请
          await OpenIM.iMManager.groupManager.joinGroup(
            groupID: groupInfo.groupID!,
            reason: '通过扫码申请加入',
            joinSource: 2,
          );
          
          IMViews.showToast('申请已发送，等待群主审核');
        }
      },
    );
  } catch (e) {
    print('加入群组失败: $e');
    IMViews.showToast('加入群聊失败，请稍后重试');
  }
}

  // 进入群聊
  Future<void> _enterGroupChat(GroupInfo groupInfo) async {
  final conversationInfo = ConversationInfo(
    conversationID: 'sg_${groupInfo.groupID}',
    conversationType: ConversationType.group,
    userID: '',
    groupID: groupInfo.groupID,
    showName: groupInfo.groupName,
    faceURL: groupInfo.faceURL,
  );
  
  AppNavigator.startChat(
    conversationInfo: conversationInfo,
  );
}

  // 尝试解析其他可能的格式
bool _tryParseAlternativeFormats(String result) {
  // 尝试解析自定义schema格式（如果主解析逻辑遗漏）
  if (result.startsWith('paxiy://')) {
    try {
      final uri = Uri.parse(result);
      if (uri.host == 'group' && uri.path.startsWith('/invite')) {
        final groupId = uri.queryParameters['groupId'];
        if (groupId != null && groupId.isNotEmpty) {
          _autoJoinGroup(groupId);
          return true;
        }
      }
    } catch (e) {
      print('解析自定义schema失败: $e');
    }
  }
  
  // 尝试JSON格式
  try {
    final Map<String, dynamic> json = jsonDecode(result);
    if (json.containsKey('userID')) {
      final userID = json['userID']?.toString();
      if (userID != null && userID.isNotEmpty) {
        PackageBridge.scanBridge?.scanOutUserID(userID);
        IMViews.showToast('识别为用户二维码，正在打开用户资料...');
        return true;
      }
    }
    if (json.containsKey('groupID') || json.containsKey('groupId')) {
      final groupID = (json['groupID'] ?? json['groupId'])?.toString();
      if (groupID != null && groupID.isNotEmpty) {
        _autoJoinGroup(groupID);
        return true;
      }
    }
    if (json.containsKey('type')) {
      final type = json['type']?.toString().toLowerCase();
      final id = json['id']?.toString();
      if (id != null && id.isNotEmpty) {
        if (type == 'user' || type == 'friend') {
          PackageBridge.scanBridge?.scanOutUserID(id);
          IMViews.showToast('识别为用户二维码，正在打开用户资料...');
          return true;
        } else if (type == 'group' || type == 'chat') {
          _autoJoinGroup(id);
          return true;
        }
      }
    }
  } catch (e) {
    // 不是JSON格式，继续尝试其他格式
  }
  
  // 智能判断ID类型
  if (result.length > 5 && result.length < 50) {
    final idType = _autoDetectIDType(result);
    if (idType == 'user') {
      PackageBridge.scanBridge?.scanOutUserID(result);
      IMViews.showToast('自动识别为用户ID，正在打开用户资料...');
      return true;
    } else if (idType == 'group') {
      _autoJoinGroup(result);
      return true;
    }
  }
  
  return false;
}
  // 自动检测ID类型
  String _autoDetectIDType(String id) {
  // 基于常见的ID格式模式进行判断
  
  // 群组ID的常见特征
  if (id.toLowerCase().contains('group') || 
      id.toLowerCase().contains('chat') ||
      id.toLowerCase().contains('room') ||
      id.toLowerCase().startsWith('g_') ||
      id.toLowerCase().startsWith('grp_') ||
      id.toLowerCase().startsWith('room_') ||
      id.toLowerCase().startsWith('chat_') ||
      id.toLowerCase().endsWith('_group') ||
      id.toLowerCase().endsWith('_chat') ||
      id.toLowerCase().endsWith('_room')) {
    return 'group';
  }
  
  // 用户ID的常见特征
  if (id.toLowerCase().contains('user') || 
      id.toLowerCase().contains('friend') ||
      id.toLowerCase().contains('member') ||
      id.toLowerCase().startsWith('u_') ||
      id.toLowerCase().startsWith('user_') ||
      id.toLowerCase().startsWith('uid_') ||
      id.toLowerCase().endsWith('_user') ||
      id.toLowerCase().endsWith('_friend') ||
      id.toLowerCase().endsWith('_member')) {
    return 'user';
  }
  
  // 基于长度判断
  // 通常群组ID会比用户ID更长，包含更多信息
  if (id.length >= 25) {
    // 很长的ID通常是群组
    return 'group';
  } else if (id.length <= 10) {
    // 很短的ID通常是用户
    return 'user';
  }
  
  // 基于字符模式判断
  // 如果包含多个下划线或连字符，可能是群组
  final underscoreCount = id.split('_').length - 1;
  final dashCount = id.split('-').length - 1;
  final dotCount = id.split('.').length - 1;
  
  if (underscoreCount >= 3 || dashCount >= 3 || dotCount >= 2) {
    return 'group';
  }
  
  // 如果是纯数字
  if (RegExp(r'^\d+$').hasMatch(id)) {
    if (id.length <= 12) {
      // 短数字ID倾向于用户ID（如QQ号、手机号等）
      return 'user';
    } else {
      // 长数字ID倾向于群组ID
      return 'group';
    }
  }
  
  // 如果包含字母数字混合
  if (RegExp(r'^[a-zA-Z0-9]+$').hasMatch(id)) {
    if (id.length >= 20) {
      // 长的字母数字混合ID倾向于群组ID
      return 'group';
    } else if (id.length <= 15) {
      // 短的字母数字混合ID倾向于用户ID
      return 'user';
    }
  }
  
  // 基于特殊字符判断
  // 包含特殊字符的ID通常是群组ID（如UUID格式）
  if (RegExp(r'[^a-zA-Z0-9_-]').hasMatch(id)) {
    return 'group';
  }
  
  // 基于大小写模式判断
  // 如果有驼峰命名或多个大写字母，可能是群组ID
  final uppercaseCount = RegExp(r'[A-Z]').allMatches(id).length;
  if (uppercaseCount >= 3) {
    return 'group';
  }
  
  // 基于常见的ID前缀判断
  final lowerID = id.toLowerCase();
  
  // 群组相关前缀
  final groupPrefixes = ['sg_', 'group_', 'grp_', 'chat_', 'room_', 'team_', 'channel_'];
  for (String prefix in groupPrefixes) {
    if (lowerID.startsWith(prefix)) {
      return 'group';
    }
  }
  
  // 用户相关前缀
  final userPrefixes = ['user_', 'u_', 'uid_', 'member_', 'usr_'];
  for (String prefix in userPrefixes) {
    if (lowerID.startsWith(prefix)) {
      return 'user';
    }
  }
  
  // 基于常见的ID后缀判断
  final groupSuffixes = ['_group', '_chat', '_room', '_team', '_channel'];
  for (String suffix in groupSuffixes) {
    if (lowerID.endsWith(suffix)) {
      return 'group';
    }
  }
  
  final userSuffixes = ['_user', '_usr', '_member', '_friend'];
  for (String suffix in userSuffixes) {
    if (lowerID.endsWith(suffix)) {
      return 'user';
    }
  }
  
  // 基于中等长度的启发式判断
  if (id.length >= 16 && id.length <= 24) {
    // 中等长度的ID，如果包含数字和字母混合，倾向于群组
    if (RegExp(r'\d').hasMatch(id) && RegExp(r'[a-zA-Z]').hasMatch(id)) {
      return 'group';
    }
  }
  
  // 如果ID看起来像UUID格式（包含连字符的长字符串）
  if (RegExp(r'^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$').hasMatch(id)) {
    return 'group';
  }
  
  // 如果ID看起来像简短的UUID（32位十六进制）
  if (RegExp(r'^[a-fA-F0-9]{32}$').hasMatch(id)) {
    return 'group';
  }
  
  // 默认返回用户类型（因为用户ID更常见，且误判用户ID的风险较小）
  return 'user';
}

  // 提取用户ID
String? _extractUserID(String result) {
  // 尝试多种格式提取用户ID
  
  // 1. 标准格式：userID=value
  RegExp regex = RegExp(r'userID=([^&\s\n\r]+)');
  Match? match = regex.firstMatch(result);
  if (match != null) {
    return Uri.decodeComponent(match.group(1)!);
  }
  
  // 2. 其他可能的用户ID格式
  final userPatterns = [
    r'user_id=([^&\s\n\r]+)',
    r'userId=([^&\s\n\r]+)',
    r'uid=([^&\s\n\r]+)',
    r'user=([^&\s\n\r]+)',
    r'member=([^&\s\n\r]+)',
    r'friend=([^&\s\n\r]+)',
    r'u=([^&\s\n\r]+)',
  ];
  
  for (String pattern in userPatterns) {
    regex = RegExp(pattern, caseSensitive: false);
    match = regex.firstMatch(result);
    if (match != null) {
      return Uri.decodeComponent(match.group(1)!);
    }
  }
  
  // 3. 冒号分隔格式：userID:value
  regex = RegExp(r'userID:([^&\s\n\r]+)', caseSensitive: false);
  match = regex.firstMatch(result);
  if (match != null) {
    return Uri.decodeComponent(match.group(1)!);
  }
  
  // 4. 简单格式检查（如果整个字符串看起来像用户ID）
  if (result.length > 3 && result.length < 50 && !result.contains('=') && !result.contains('&')) {
    // 检查是否包含用户ID的特征
    final lowerResult = result.toLowerCase();
    if (lowerResult.contains('user') || 
        lowerResult.startsWith('u_') || 
        lowerResult.endsWith('_user') ||
        RegExp(r'^\d{5,15}$').hasMatch(result)) { // 5-15位数字（如QQ号）
      return result.trim();
    }
  }
  
  return null;
}

// 提取群组ID
String? _extractGroupID(String result) {
  // 尝试多种格式提取群组ID
  
  // 1. 标准格式：groupID=value
  RegExp regex = RegExp(r'groupID=([^&\s\n\r]+)');
  Match? match = regex.firstMatch(result);
  if (match != null) {
    return Uri.decodeComponent(match.group(1)!);
  }
  
  // 2. 其他可能的群组ID格式
  final groupPatterns = [
    r'group_id=([^&\s\n\r]+)',
    r'groupId=([^&\s\n\r]+)',
    r'gid=([^&\s\n\r]+)',
    r'group=([^&\s\n\r]+)',
    r'chat=([^&\s\n\r]+)',
    r'chatId=([^&\s\n\r]+)',
    r'chat_id=([^&\s\n\r]+)',
    r'room=([^&\s\n\r]+)',
    r'roomId=([^&\s\n\r]+)',
    r'room_id=([^&\s\n\r]+)',
    r'team=([^&\s\n\r]+)',
    r'teamId=([^&\s\n\r]+)',
    r'team_id=([^&\s\n\r]+)',
    r'channel=([^&\s\n\r]+)',
    r'channelId=([^&\s\n\r]+)',
    r'channel_id=([^&\s\n\r]+)',
    r'g=([^&\s\n\r]+)',
  ];
  
  for (String pattern in groupPatterns) {
    regex = RegExp(pattern, caseSensitive: false);
    match = regex.firstMatch(result);
    if (match != null) {
      return Uri.decodeComponent(match.group(1)!);
    }
  }
  
  // 3. 冒号分隔格式：groupID:value
  regex = RegExp(r'groupID:([^&\s\n\r]+)', caseSensitive: false);
  match = regex.firstMatch(result);
  if (match != null) {
    return Uri.decodeComponent(match.group(1)!);
  }
  
  // 4. 简单格式检查（如果整个字符串看起来像群组ID）
  if (result.length > 5 && result.length < 100 && !result.contains('=') && !result.contains('&')) {
    // 检查是否包含群组ID的特征
    final lowerResult = result.toLowerCase();
    if (lowerResult.contains('group') || 
        lowerResult.contains('chat') ||
        lowerResult.contains('room') ||
        lowerResult.startsWith('g_') || 
        lowerResult.startsWith('grp_') ||
        lowerResult.startsWith('sg_') ||
        lowerResult.startsWith('chat_') ||
        lowerResult.startsWith('room_') ||
        lowerResult.endsWith('_group') ||
        lowerResult.endsWith('_chat') ||
        lowerResult.endsWith('_room') ||
        RegExp(r'^[a-fA-F0-9]{20,}$').hasMatch(result) || // 长十六进制字符串
        RegExp(r'^[a-zA-Z0-9]{20,}$').hasMatch(result)) { // 长字母数字字符串
      return result.trim();
    }
  }
  
  return null;
}

}

